'''
Created on Jan 28, 2014

@author: dmen
'''
import pycurl
import httplib
from httplib import HTTP
from com.ad.sword.dao.models import HttpTask, Alarm
from com.ad.sword.utils import SMS
from com.ad.sword.utils.Mail import send_email, send_text_email
from django.utils.translation import ugettext_lazy as _
from com.ad.sword.web.common import get_config

class TaskExecutor:
    def __init__(self,task):
        self.task=task
    def execute(self):
        pass
    
    
class HTTPMonitorExcutor(TaskExecutor):
    def execute(self):
        c = pycurl.Curl()
        monitorTask=HttpTask.objects.get(task=self.task['id'])
        c.setopt(pycurl.URL,str(monitorTask.url))
        result=False
        try:
            c.perform()
            code=c.getinfo(pycurl.HTTP_CODE)
            if  code == httplib.OK:
                result=True
        except Exception:
            result=False
        r=int(monitorTask.result)
        monitorTask.result=( (r<<1)+result)&(1<<int(monitorTask.alarm_policy)-1)
        if not int(monitorTask.result):
            alarm=Alarm()
            alarm.info="Monitor alarm"
            alarm.save()
            if 'E' in monitorTask.notify_types:
                email = get_config("alarm_email")
                if email:
                    send_text_email("App monitor alarm",email, alarm.info)
            if 'S' in monitorTask.notify_types:
                number = get_config("alarm_sms_number")
                if number:
                    SMS.sms(number, alarm.info)
        monitorTask.save()
        
    